package com.itqf.controller;

import com.itqf.exception.UserException;
import com.itqf.pojo.User;
import com.itqf.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * projectName: rbacgp8
 *
 * @author: 赵伟风
 * time: 2021/8/12 11:12
 * description:
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("unauthentication")
    public String unauthentication(){

        return "unauthentication";
    }

    @GetMapping("unauthorization")
    public String unauthorization(){

        return "unauthorization";
    }



    @GetMapping("login")
    public String jump(){

        return "login";
    }


    @PostMapping("deal")
    public String deal(User user, HttpSession session) throws AuthenticationException, UserException {

        //没有权限管理的登录 验证账号密码是否正确,直接跳转到程序首页
        //权限管理的登录 验证账号密码是否正确,不正确,正常提示,正确,查询账号的权限[菜单],动态首页展示


        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(user.getuAccount(), user.getuPassword());

        try {
            subject.login(token);
        }catch (AuthenticationException ex)
        {

            throw  ex;
        }

        System.out.println(subject.isAuthenticated());

        user = (User) subject.getPrincipal();

        Map<String, Object> data = userService.login(user);
//
//        Map<String,Object> data = userService.login(user);
//        //user user / permissions List<permission>
//
        session.setAttribute("data", data);

        return "index";
    }


    @GetMapping("logout")
    public String logout(HttpSession session){

        session.removeAttribute("data");

        return "login";
    }

}
